<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <a-modal title="选择导出年份" v-model="yearModalVisible" :mask-closable="false" :footer="null" width="400">
      <div style="padding: 20px 0;">
        <a-select v-model="selectedYear" placeholder="请选择年份" style="width: 100%;">
          <!-- 动态渲染前5年、当年、后5年 -->
          <a-select-option v-for="option in yearOptions" :key="option.value" :value="option.value">
            {{ option.label }} <!-- 只显示label文本 -->
          </a-select-option>
        </a-select>
      </div>
      <div style="text-align: right;">
        <a-button style="margin-right: 8px;" @click="handleDirectExport">
          直接导出
        </a-button>
        <a-button type="primary" @click="handleConfirmExport">
          确定导出
        </a-button>
      </div>
    </a-modal>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="showYearModal">
        导出表单
      </a-button>
      <!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl"-->
      <!--        @change="handleImportExcel">-->
      <!--        <a-button type="primary" icon="import">导入</a-button>-->
      <!--      </a-upload>-->
      <!-- 高级查询区域 -->
      <!--      <j-super-query :fieldList="superFieldList" ref="superQueryModal"-->
      <!--        @handleSuperQuery="handleSuperQuery"></j-super-query>-->
      <!-- 新增：全部提交审核按钮 -->
      <!--      <a-button type="primary" icon="check-circle" style="margin-left: 8px" @click="handleAllSubmit">-->
      <!--        全部提交审核-->
      <!--      </a-button>-->
      <a-button type="primary" icon="check-circle" style="margin-left: 8px" @click="submitBatch">
        批量提交
      </a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{
          selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table ref="table" size="middle" :scroll="{ x: true }" bordered rowKey="id" :columns="columns"
        :dataSource="dataSource" :pagination="ipagination" :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text,record">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt=""
            style="max-width:80px;font-size: 12px;font-style: italic;" />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <template slot="action" slot-scope="text, record" class="action-buttons">
          <!-- 1. 编辑按钮：排除【通过】【待审批】状态 -->
          <template v-if="record.status !== '通过' && record.status !== '待审批' && record.status !== '第一人审批同意'">
            <a @click="handleEdit(record)" class="action-item">编辑</a>
          </template>

          <!-- 2. 编辑-提交分界线：仅在【有编辑按钮】且【有提交按钮】时显示 -->
          <template v-if="record.status === '驳回' || record.status === '待提交'">
            <span class="divider">|</span>
          </template>

          <!-- 3. 提交按钮：仅【驳回】【待提交】显示 -->
          <template
            v-if="(record.status === '驳回' || record.status === '待提交') && record.status !== '通过' && record.status !== '第一人审批同意'">
            <a-popconfirm title="确定提交吗?" @confirm="() => handleSubmit(record.id)">
              <a class="action-item">提交</a>
            </a-popconfirm>
          </template>

          <!-- 4. 操作-审批详情分界线：仅在【有编辑/提交按钮】时显示 -->
          <template v-if="record.status === '驳回' || record.status === '待提交'">
            <span class="divider">|</span>
          </template>

          <!-- 5. 审批详情：所有状态均显示（待审批时仅显示此内容） -->
          <a @click="openApprovalMessageDrawer(record.id)" class="action-item">审批详情</a>
        </template>
      </a-table>
    </div>
    <!-- table区域 end -->
    <!-- 审批详情抽屉 -->
    <cw-approval-message-drawer ref="approvalMessageDrawer" @ok="handleApprovalMessageOk"></cw-approval-message-drawer>

    <cw-gyjfsz-modal ref="modalForm" @ok="modalFormOk"></cw-gyjfsz-modal>
  </a-card>
</template>

<script>

import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import CwGyjfszModal from './modules/CwGyjfszModal'
import { httpAction, getAction } from '@/api/manage'
import axios from 'axios'
import CwApprovalMessageDrawer from './modules/CwApprovalMessageModal.Style#Drawer.vue'

export default {
  name: 'CwGyjfszList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    CwApprovalMessageDrawer,
    CwGyjfszModal
  },
  data() {
    return {
      yearModalVisible: false, // 年份弹窗显示状态
      selectedYear: null, // 选中的年份
      yearOptions: [],// 年份选项列表（前5年-当年-后5年）
      description: '公用经费收支管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '经济分类科目',
          align: "center",
          dataIndex: 'jflx'
        },
        {
          title: '项目名称',
          align: "center",
          dataIndex: 'xmmc'
        },
        {
          title: '年度',
          align: "center",
          dataIndex: 'nd'
        },
        {
          title: '单位',
          align: "center",
          dataIndex: 'dw'
        },
        {
          title: '办公费',
          align: "center",
          dataIndex: 'bgf'
        },
        {
          title: '印刷费',
          align: "center",
          dataIndex: 'ysf'
        },
        {
          title: '手续费',
          align: "center",
          dataIndex: 'sxf'
        },
        {
          title: '水费',
          align: "center",
          dataIndex: 'sf'
        },
        {
          title: '电费',
          align: "center",
          dataIndex: 'df'
        },
        {
          title: '邮电费',
          align: "center",
          dataIndex: 'ydf'
        },
        {
          title: '取暖费',
          align: "center",
          dataIndex: 'qnf'
        },
        {
          title: '物业管理费',
          align: "center",
          dataIndex: 'wyglf'
        },
        {
          title: '差旅费',
          align: "center",
          dataIndex: 'clf'
        },
        {
          title: '因公出境费用',
          align: "center",
          dataIndex: 'ygcjf'
        },
        {
          title: '维护费',
          align: "center",
          dataIndex: 'whf'
        },
        {
          title: '租赁费',
          align: "center",
          dataIndex: 'zlf'
        },
        {
          title: '会议费',
          align: "center",
          dataIndex: 'hyf'
        },
        {
          title: '培训费',
          align: "center",
          dataIndex: 'pxf'
        },
        {
          title: '公务接待费',
          align: "center",
          dataIndex: 'gwjd'
        },
        {
          title: '专用材料费',
          align: "center",
          dataIndex: 'zycl'
        },
        {
          title: '被装购置费',
          align: "center",
          dataIndex: 'bzgzf'
        },
        {
          title: '专用燃料费',
          align: "center",
          dataIndex: 'zyrlf'
        },
        {
          title: '劳务费',
          align: "center",
          dataIndex: 'lwf'
        },
        {
          title: '委托业务费',
          align: "center",
          dataIndex: 'wtywf'
        },
        {
          title: '工会经费',
          align: "center",
          dataIndex: 'ghjf'
        },
        {
          title: '公务用车运行维护费',
          align: "center",
          dataIndex: 'gwcyc'
        },
        {
          title: '其他交通费用',
          align: "center",
          dataIndex: 'qtjtfy'
        },
        {
          title: '税金及附加费用',
          align: "center",
          dataIndex: 'sj'
        },
        {
          title: '其他商品和服务支出',
          align: "center",
          dataIndex: 'qtsp'
        },
        {
          title: '房屋建筑物购建',
          align: "center",
          dataIndex: 'fw'
        },
        {
          title: '办公设备购置',
          align: "center",
          dataIndex: 'bg'
        },
        {
          title: '专用设备购置',
          align: "center",
          dataIndex: 'zy'
        },
        {
          title: '基础设施建设',
          align: "center",
          dataIndex: 'jc'
        },
        {
          title: '大型修缮',
          align: "center",
          dataIndex: 'dx'
        },
        {
          title: '信息网络及软件购置更新',
          align: "center",
          dataIndex: 'xx'
        },
        {
          title: '物资储备',
          align: "center",
          dataIndex: 'wz'
        },
        {
          title: '土地补偿',
          align: "center",
          dataIndex: 'td'
        },
        {
          title: '安置补助',
          align: "center",
          dataIndex: 'az'
        },
        {
          title: '地上附着物和青苗补偿',
          align: "center",
          dataIndex: 'dsfzw'
        },
        {
          title: '拆迁补偿',
          align: "center",
          dataIndex: 'cq'
        },
        {
          title: '公务用车购置',
          align: "center",
          dataIndex: 'gwc'
        },
        {
          title: '其他交通工具购置',
          align: "center",
          dataIndex: 'qtjt'
        },
        {
          title: '文物和陈列品购置',
          align: "center",
          dataIndex: 'wwcl'
        },
        {
          title: '无形资产购置',
          align: "center",
          dataIndex: 'wxzcgz'
        },
        {
          title: '其他资本性支出',
          align: "center",
          dataIndex: 'qtzbszc'
        },
        {
          title: '基本收入总额',
          align: "center",
          dataIndex: 'jbsrze'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          fixed: "right",
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        daochu: "/cw/cwGyjfsz/gongyong/export",
        list: "/cw/cwGyjfsz/list",
        delete: "/cw/cwGyjfsz/delete",
        deleteBatch: "/cw/cwGyjfsz/deleteBatch",
        exportXlsUrl: "/cw/cwGyjfsz/exportXls",
        importExcelUrl: "cw/cwGyjfsz/importExcel",
        submitSingle: "/cw/cwGyjfsz/submitSingle", // 单行提交
        submitBatch: "/cw/cwGyjfsz/submitBatch",   // 批量提交
        submitAll: "/cw/cwGyjfsz/submitAll"        // 全部提交

      },
      dictOptions: {},
      superFieldList: [],
    }
  },
  created() {
    this.getSuperFieldList();
    this.generateYearOptions(); // 新增：生成年份选项
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    },
  },
  methods: {
    // 打开审批详情抽屉
    openApprovalMessageDrawer(recordId) {
      this.$refs.approvalMessageDrawer.open(recordId)
    },
    // 审批详情抽屉确认回调
    handleApprovalMessageOk() {
      // 可在此处处理刷新逻辑（如刷新当前列表）
    },
    generateYearOptions() {
      const currentYear = new Date().getFullYear(); // 获取当前年份，例如2025
      const options = [];

      // 前5年：当前年-5 到 当前年-1（按从早到晚的顺序）
      for (let i = 5; i >= 1; i--) {
        const year = currentYear - i;
        options.push({ label: `${year}年一上`, value: `${year}年一上` });
        options.push({ label: `${year}年二上`, value: `${year}年二上` });
      }

      // 当前年份
      options.push({ label: `${currentYear}年一上`, value: `${currentYear}年一上` });
      options.push({ label: `${currentYear}年二上`, value: `${currentYear}年二上` });

      // 后5年：当前年+1 到 当前年+5（按从早到晚的顺序）
      for (let i = 1; i <= 5; i++) {
        const year = currentYear + i;
        options.push({ label: `${year}年一上`, value: `${year}年一上` }); // 修复了此处的笔误
        options.push({ label: `${year}年二上`, value: `${year}年二上` });
      }

      this.yearOptions = options;
      this.selectedYear = `${currentYear}年一上`; // 默认选中当前年份的第一个选项
    },
    showYearModal() {
      this.yearModalVisible = true; // 打开年份选择弹窗
    },
    // 2. 新增：弹窗“直接导出”按钮逻辑（无年份参数）
    handleDirectExport() {
      this.yearModalVisible = false; // 关闭弹窗
      this.daochu('公用经费收支', null); // 调用导出方法，年份传null
    },
    // 3. 新增：弹窗“确定导出”按钮逻辑（带年份参数）
    handleConfirmExport() {
      if (!this.selectedYear) { // 校验是否选择年份
        this.$message.warning('请选择导出年份');
        return;
      }
      this.yearModalVisible = false; // 关闭弹窗
      this.daochu('公用经费收支', this.selectedYear); // 调用导出方法，传递选中年份
    },
    /**
 * 1. 单行提交审核
 * @param {Object} record - 单行数据
 */
    // 提交处理方法
    handleSubmit(id) {
      if (!id) {
        this.$message.error('缺少记录ID')
        return
      }

      this.loading = true
      this.$http({
        url: this.url.submitSingle,
        method: 'post',
        headers: this.tokenHeader,
        params: { id: id, status: '待审批' }
      }).then(res => {
        if (res.success) {
          this.$message.success('提交成功！')
          this.loadData() // 刷新列表
        } else {
          this.$message.error(res.message || '提交失败')
        }
      }).catch(err => {
        this.$message.error('提交出错：' + (err.message || err.toString()))
      }).finally(() => {
        this.loading = false
      })
    },

    /**
     * 2. 批量提交审核（基于选中的行）
     */
    /**
     * 2. 批量提交审核（基于选中的行）
     */
    /**
     * 批量提交审核
     */
    submitBatch() {
      if (this.selectedRowKeys.length === 0) {
        this.$message.warning('请选择要提交的数据');
        return;
      }
      this.$confirm({
        title: '批量提交确认',
        content: `确定要提交选中的${this.selectedRowKeys.length}条数据吗？`,
        onOk: () => {
          this.loading = true;
          this.$http({
            url: this.url.submitBatch,
            method: 'put',
            params: {
              ids: this.selectedRowKeys.join(','),
              status: '待审批'
            } // 参数拼接到URL
          }).then(res => {
            if (res.success) {
              this.$message.success('批量提交成功');
              this.selectedRowKeys = []; // 清空选中状态
              this.loadData(); // 重新加载数据
            } else {
              this.$message.error('批量提交失败：' + res.message);
            }
          }).finally(() => {
            this.loading = false;
          });
        }
      });
    },
    /**
     * 3. 全部数据提交审核
     */
    handleAllSubmit() {
      this.$confirm({
        title: '全部提交确认',
        content: '确定要将所有数据提交审核吗？此操作会覆盖所有数据的状态为“已提交”',
        onOk: async () => {
          this.loading = true;
          try {
            // 调用全部提交接口
            const res = await httpAction(this.url.submitAll, {
              status: '已提交'
            }, 'put');
            if (res.success) {
              this.$message.success('全部数据提交审核成功');
              this.loadData(); // 重新加载列表
            } else {
              this.$message.error(res.message || '全部提交审核失败');
            }
          } catch (err) {
            this.$message.error('全部提交异常，请重试');
            console.error(err);
          } finally {
            this.loading = false;
          }
        }
      });
    },
    // 4. 修改原daochu方法：新增year参数，支持传递年份
    // 修复后的导出方法（确保Excel正常下载）
    daochu(title, year) {
      this.loading = true;
      // 处理请求参数
      const params = year ? { year: year } : {};

      // 使用原生XMLHttpRequest确保文件流处理正确（避免axios封装问题）
      const xhr = new XMLHttpRequest();
      const url = `${window._CONFIG['domianURL']}${this.url.daochu}`;

      // 拼接参数到URL（get请求参数必须在URL上）
      const queryString = Object.keys(params).map(key => `${key}=${encodeURIComponent(params[key])}`).join('&');
      const fullUrl = queryString ? `${url}?${queryString}` : url;

      xhr.open('GET', fullUrl, true);
      xhr.setRequestHeader('X-Access-Token', localStorage.getItem('X-Access-Token'));
      xhr.responseType = 'blob'; // 关键：指定响应类型为blob

      xhr.onload = () => {
        this.loading = false;
        if (xhr.status === 200) {
          const blob = xhr.response;
          // 处理文件名（从响应头获取或使用默认）
          let fileName = title || '公用经费收支报表';
          const contentDisposition = xhr.getResponseHeader('content-disposition');
          if (contentDisposition && contentDisposition.includes('filename=')) {
            fileName = decodeURIComponent(contentDisposition.split('filename=')[1].replace(/"/g, ''));
          } else {
            fileName += '.xlsx'; // 确保文件后缀正确
          }

          // 兼容所有浏览器的下载方式
          if (window.navigator.msSaveOrOpenBlob) {
            // IE/Edge浏览器
            window.navigator.msSaveOrOpenBlob(blob, fileName);
          } else {
            // 其他浏览器
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = fileName;
            document.body.appendChild(link);
            link.click();
            // 清理资源
            setTimeout(() => {
              document.body.removeChild(link);
              URL.revokeObjectURL(url);
            }, 100);
          }
          this.$message.success('导出成功');
        } else {
          this.$message.error('导出失败：' + xhr.statusText);
        }
      };

      xhr.onerror = () => {
        this.loading = false;
        this.$message.error('导出请求失败，请重试');
      };

      xhr.send(); // 发送请求
    },

    initDictConfig() {
    },
    getSuperFieldList() {
      let fieldList = [];
      fieldList.push({ type: 'string', value: 'jflx', text: '经济分类科目', dictCode: '' })
      fieldList.push({ type: 'string', value: 'xmmc', text: '项目名称', dictCode: '' })
      fieldList.push({ type: 'string', value: 'nd', text: '年度', dictCode: '' })
      fieldList.push({ type: 'string', value: 'dw', text: '单位', dictCode: '' })
      fieldList.push({ type: 'string', value: 'bgf', text: '办公费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'ysf', text: '印刷费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'sxf', text: '手续费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'sf', text: '水费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'df', text: '电费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'ydf', text: '邮电费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'qnf', text: '取暖费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'wyglf', text: '物业管理费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'clf', text: '差旅费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'ygcjf', text: '因公出境费用', dictCode: '' })
      fieldList.push({ type: 'string', value: 'whf', text: '维护费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'zlf', text: '租赁费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'hyf', text: '会议费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'pxf', text: '培训费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'gwjd', text: '公务接待费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'zycl', text: '专用材料费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'bzgzf', text: '被装购置费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'zyrlf', text: '专用燃料费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'lwf', text: '劳务费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'wtywf', text: '委托业务费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'ghjf', text: '工会经费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'gwcyc', text: '公务用车运行维护费', dictCode: '' })
      fieldList.push({ type: 'string', value: 'qtjtfy', text: '其他交通费用', dictCode: '' })
      fieldList.push({ type: 'string', value: 'sj', text: '税金及附加费用', dictCode: '' })
      fieldList.push({ type: 'string', value: 'qtsp', text: '其他商品和服务支出', dictCode: '' })
      fieldList.push({ type: 'string', value: 'fw', text: '房屋建筑物购建', dictCode: '' })
      fieldList.push({ type: 'string', value: 'bg', text: '办公设备购置', dictCode: '' })
      fieldList.push({ type: 'string', value: 'zy', text: '专用设备购置', dictCode: '' })
      fieldList.push({ type: 'string', value: 'jc', text: '基础设施建设', dictCode: '' })
      fieldList.push({ type: 'string', value: 'dx', text: '大型修缮', dictCode: '' })
      fieldList.push({ type: 'string', value: 'xx', text: '信息网络及软件购置更新', dictCode: '' })
      fieldList.push({ type: 'string', value: 'wz', text: '物资储备', dictCode: '' })
      fieldList.push({ type: 'string', value: 'td', text: '土地补偿', dictCode: '' })
      fieldList.push({ type: 'string', value: 'az', text: '安置补助', dictCode: '' })
      fieldList.push({ type: 'string', value: 'dsfzw', text: '地上附着物和青苗补偿', dictCode: '' })
      fieldList.push({ type: 'string', value: 'cq', text: '拆迁补偿', dictCode: '' })
      fieldList.push({ type: 'string', value: 'gwc', text: '公务用车购置', dictCode: '' })
      fieldList.push({ type: 'string', value: 'qtjt', text: '其他交通工具购置', dictCode: '' })
      fieldList.push({ type: 'string', value: 'wwcl', text: '文物和陈列品购置', dictCode: '' })
      fieldList.push({ type: 'string', value: 'wxzcgz', text: '无形资产购置', dictCode: '' })
      fieldList.push({ type: 'string', value: 'qtzbszc', text: '其他资本性支出', dictCode: '' })
      fieldList.push({ type: 'string', value: 'jbsrze', text: '基本收入总额', dictCode: '' })
      this.superFieldList = fieldList
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>